<template>
  <div class="menu-tree">
    <a-spin :loading="loading">
      <a-tree
        v-model:checked-keys="checkedKeys"
        :data="treeData"
        checkable
        :default-expanded-keys="expandedKeys"
        :check-strictly="false"
        :auto-expand-parent="true"
        @check="handleCheck"
      />
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { getMenuTree, MenuItem } from '@/api/system/menu';

  // Props定义
  const props = defineProps({
    menuIds: {
      type: Array as () => number[],
      default: () => [],
    },
  });

  // Emits定义
  const emit = defineEmits(['update:menuIds']);

  // 加载状态
  const loading = ref(false);

  // 树形数据
  const treeData = ref<any[]>([]);

  // 选中的节点
  const checkedKeys = ref<(string | number)[]>([]);

  // 展开的节点
  const expandedKeys = ref<(string | number)[]>([]);

  // 格式化菜单数据为树形结构
  const formatMenuTree = (data: MenuItem[]) => {
    return data.map((item) => ({
      key: item.id,
      title: item.name,
      children:
        item.children && item.children.length > 0
          ? formatMenuTree(item.children)
          : undefined,
    }));
  };

  // 处理选中事件
  const handleCheck = (checkedKeys: (string | number)[]) => {
    emit(
      'update:menuIds',
      checkedKeys.map((k) => Number(k))
    );
  };

  // 获取菜单树形数据
  const fetchMenuTree = async () => {
    loading.value = true;
    try {
      const res = await getMenuTree();
      treeData.value = formatMenuTree(res.data);

      // 获取所有节点的ID作为可展开的节点
      const allKeys: (string | number)[] = [];
      const collectKeys = (items: any[]) => {
        items.forEach((item) => {
          allKeys.push(item.key);
          if (item.children && item.children.length > 0) {
            collectKeys(item.children);
          }
        });
      };

      collectKeys(treeData.value);
      expandedKeys.value = allKeys;
    } catch (error) {
      console.error('获取菜单树形数据出错:', error);
      Message.error('获取菜单数据失败');
    } finally {
      loading.value = false;
    }
  };

  // 监听menuIds变化
  watch(
    () => props.menuIds,
    (newVal) => {
      checkedKeys.value = newVal || [];
    },
    { immediate: true, deep: true }
  );

  // 组件挂载时获取菜单数据
  onMounted(() => {
    fetchMenuTree();
  });
</script>

<style scoped lang="less">
  .menu-tree {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px 0;
  }
</style>
